﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Windows;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Database;
using ReflectionStudio.Core.Events;
using FLTVAGSAB;
using System.Linq;
using INTEX.DataBase.Tools;
namespace WPFExcelReport
{
    public partial class FLTVAGSABData
    {
        public string ApplicationPath
        {
            get { return System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); }
        }
        public void SetUpCADTable()
        {
            CADTable.Add("TechMaster", null);
            CADTable.Add("TechDetail", null);
        }
        /// <summary>
        /// GetJob is used to collect the tasks to finish the order creation
        /// </summary>
        /// <param name="FInterID"></param>
        /// <returns></returns>
        public DataSet GetJob()
        {

            ArrayList tbs = new ArrayList() { "A", "B", "C" };
            string a = (string)tbs[0];
            DataSet Result = new DataSet();
            DataSet Return = new DataSet();

            try
            {
                string fileDone;
                string filestemp = @"C:\IntexReport\Data\FLTVAGSAB\01Temp";
                string[] files = System.IO.Directory.GetFiles(filestemp);
                foreach (string file in files)
                {
                    fileDone = file.Replace(@"\01Temp\", @"\02Incoming\");
                    System.IO.File.Move(file, fileDone);
                }
                string files2p = @"C:\IntexReport\Data\FLTVAGSAB\02Incoming";
                files = System.IO.Directory.GetFiles(files2p);

                if (files.Length > 0)
                {
                    string file = files[0];
                    Result.ReadXml(file);
                    Return.Merge(Result);
                    fileDone = file.Replace(@"\02Incoming\", @"\03Done\");
                    System.IO.File.Move(file, fileDone);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {

            }
            return Return;
        }
        public void SaveJob(DataSet SetOrder)
        {
            ArrayList tbs = new ArrayList() { "A", "B", "C" };
            string a = (string)tbs[0];
            DataSet Result = new DataSet();
            DataSet Return = new DataSet();
            string fileroot = @"C:\IntexReport\Data\FLTVAGSAB\01Temp\" + "VVVK" + DateTime.Now.ToFileTime().ToString() + ".XML";
            SetOrder.WriteXml(fileroot);
        }
        private DataSet CheckABPART(DataSet src, string file)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            var query = from dwVA10 in src.Tables["ABPOS_EXT"].AsEnumerable()
                        select new
                        {
                            VAFKOLL = dwVA10.Field<string>("VAFKOLL"),
                            VAFART = dwVA10.Field<string>("VAFART"),
                            VAFFARBE = dwVA10.Field<string>("VAFFARBE"),
                        };
            foreach (var dwVA10 in query)
            {
                string coll, art, color;
                coll = Left(dwVA10.VAFKOLL + "            ", 5);
                art = Left(dwVA10.VAFART + "                      ", 24);
                color = Left(dwVA10.VAFFARBE + "               ", 10);
                setResult = INTEXDBC.QueryVAFARBEN("00", coll, art, color);
                if (setResult.Tables.Count == 0)
                    continue;
                if (setResult.Tables[0].Rows.Count == 0)
                    continue;
                DataRow rowVA10 = setResult.Tables[0].Rows[0];
                var query1 = from row in src.Tables["ABPOS_EXT"].AsEnumerable()
                             where row["VAFKOLL"] == dwVA10.VAFKOLL
                             & row["VAFART"] == dwVA10.VAFART
                             & row["VAFFARBE"] == dwVA10.VAFFARBE
                             select row;
                foreach (DataRow row in query1)
                {
                    row["ABPART"] = rowVA10["VAFPART"];
                    row["ABPVAR"] = rowVA10["VAFPVAR"];
                    row["ABPFARBE"] = rowVA10["VAFFFARBE"];
                }
            }
            exAgent.SetCurrentSheet("ABPOS_EXT");
            int x = 3;
            int y = 1;
            foreach (DataRow row in src.Tables["ABPOS_EXT"].Rows)
            {
                y = 1;
                foreach (DataColumn dc in src.Tables["ABPOS_EXT"].Columns)
                {
                    exAgent.SetCellValue(x, y, row[dc.ColumnName].ToString());
                    y++;
                }
                x++;
            }
            exAgent.Save();
            setReturn.Merge(src);
            return setReturn;
        }
        private DataSet CheckGS08(DataSet src, string file)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();

            var query = from dwABPOS in src.Tables["ABPOS_EXT"].AsEnumerable()
                        select new
                       {
                           ABPART = dwABPOS.Field<string>("ABPART"),
                       };
            
            string processedyarn = "";
            foreach (var dwABPOS in query)
            {
                string var, art, color;
                art = Left(dwABPOS.ABPART+ "            ", 20);
                if(processedyarn.Contains(art+";"))
                    continue;
                processedyarn += art + ";";
                setResult = INTEXDBC.QueryGASTGA(art);
                var query1 = from rowx in src.Tables["ABPOS_EXT"].AsEnumerable()
                             where rowx["ABPART"].ToString().Trim() == art.Trim()
                             & rowx["GS08"].ToString().Trim() == "N"
                             select rowx;
                foreach (DataRow row in query1)
                {
                    
                    var query2 = from rowg in setResult.Tables["GASTGA"].AsEnumerable()
                                 where rowg["GAGART"].ToString().Trim() == row["ABPART"].ToString().Trim()
                                 & rowg["GAGVAR"].ToString().Trim() == row["ABPVAR"].ToString().Trim()
                                 & rowg["GAGFARBE"].ToString().Trim() == row["ABPFARBE"].ToString().Trim()
                                 select row;
                    if (query2.Count() > 0)
                    {
                        row["GS08"] = "Y";
                    }
                }
            } 
            exAgent.SetCurrentSheet("ABPOS_EXT");
            int x = 3;
            int y = 1;
            foreach (DataRow row in src.Tables["ABPOS_EXT"].Rows)
            {
                y = 1;
                foreach (DataColumn dc in src.Tables["ABPOS_EXT"].Columns)
                {
                    exAgent.SetCellValue(x, y, row[dc.ColumnName].ToString());
                    y++;
                }
                x++;
            }
            exAgent.Save();
            setReturn.Merge(src);
            return setReturn;
        }
        private DataSet ConsolidateData(DataSet src, string file)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            bool IsCheckABPART = false;
            bool IsCheckGS08 = true;
            try
            {
                //获取ABPOS_EXT的VA10
                //查找对应的GS07
                //更新ABPOS_EXT
                //更新EXCEL
                if (!src.Tables.Contains("ABPOS_EXT"))
                {
                    setReturn.Merge(src);
                    return setReturn;
                }
                if (src.Tables["ABPOS_EXT"].Rows.Count == 0)
                {
                    setReturn.Merge(src);
                    return setReturn;
                }
                if (IsCheckABPART)
                {
                    setResult=CheckABPART(src, file);
                    setReturn.Merge(setResult);
                }
                if (IsCheckGS08)
                {
                    setResult=CheckGS08(src, file);
                    setReturn.Merge(setResult);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        public DataSet LoadExcelVKVV()
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            try
            {
                #region=======MAPINTEX================
                string fileroot = @"C:\IntexReport\Data\FLTVAGSAB\EXCEL";
                string[] files = System.IO.Directory.GetFiles(fileroot);
                foreach (string file in files)
                {
                    string ShortName = file.Substring(file.LastIndexOf("\\") + 1);
                    EventDispatcher.Instance.RaiseStatus("装载:" + ShortName + "开始", StatusEventType.StopProgress);
                    if (!ShortName.StartsWith("VAGSAB"))
                        continue;
                    if (exAgent == null)
                    {
                        exAgent = new ExcelX.ExcelLib.ExcelAgent(file);
                    }
                    if (System.IO.File.Exists(file))
                    {
                        setResult = new DataSet();
                        setResult = exAgent.LoadDataTableDef(file, "", 50);
                        setResult = ConsolidateData(setResult, file);
                        setReturn.Merge(setResult);
                        string xml = @"C:\IntexReport\Data\FLTVAGSAB\01Temp\" + ShortName.Replace(".xls", "_" + DateTime.Now.ToFileTime().ToString() + ".XML");
                        if (System.IO.File.Exists(xml))
                        {
                            System.IO.File.Delete(xml);
                        }
                        if (setResult != null)
                        {
                            setResult.WriteXml(xml);
                        }
                        System.IO.File.Copy(file, fileroot + "\\P_" + ShortName);
                        exAgent.Close();
                        System.IO.File.Delete(file);
                        EventDispatcher.Instance.RaiseStatus("装载:" + ShortName + "完成", StatusEventType.StopProgress);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                if (exAgent != null)
                {
                    exAgent.KillExcelProcess();
                    exAgent.Dispose();
                    GC.Collect();
                    exAgent.Close();
                    exAgent = null;
                }
            }
            return setReturn;
        }

    }
}
